URL = "http://protobuf.googlecode.com/files/protobuf-%(VERSION)s.tar.gz"
VERSIONS = ["2.4.1"]
DEFAULT_VERSION = "2.4.1"
REQUIRES = ["java"]
#DEPENDS = ["zlib"]

from source.builders import VisualStudioBuilder, ConfigureMakeBuilder, BuildException
import os, shutil, ext.patch, glob

class ProtoBufConfigureMakeBuilder( ConfigureMakeBuilder ):

  def configureparameters(self):
    params = ["--without-zlib"]
    return params
    
  def install(self):
    ConfigureMakeBuilder.install(self)

    # Compile and install Java interface
    os.chdir( self.extractedpath + "/java/" )
    self.execute( self.targetpath() + "/bin/protoc --java_out=src/main/java -I../src ../src/google/protobuf/descriptor.proto" )
    self.copydir( "src/main/java", self.targetpath() + "/java" )
    


class ProtoBufVisualStudioBuilder( VisualStudioBuilder ):
  """ subclass of VisualStudioBuilder with customized steps """
    
#  def hasdebug(self):
#    #done by make function
#    return False

#  def configure (self):
#    self.replaceLinesInFile( self.extractedpath+"\\vsprojects\\config.h", [( "// #define HAVE_ZLIB 1", "#define HAVE_ZLIB 1" )] )

  def patch(self):
    os.chdir( self.extractedpath+"\\vsprojects\\" )
    if self.machine.bits == 64:
      self.convertProjTo64("libprotobuf.vcproj")
      self.convertProjTo64("libprotoc.vcproj")
      self.convertProjTo64("protoc.vcproj")
      self.convertSolutionTo64("protobuf.sln")

    patchstr = """
--- libprotobuf.vcproj
+++ libprotobuf.vcproj
@@ -4,6 +4,7 @@
 \tVersion="9.00"
 \tName="libprotobuf"
 \tProjectGUID="{3E283F37-A4ED-41B7-A3E6-A2D89D131A30}"
+\tRootNamespace="libprotobuf"
 \tKeyword="Win32Proj"
 \tTargetFrameworkVersion="131072"
 \t>
"""
    p = ext.patch.fromstring(patchstr)
    print "Patch applied: ", p.apply()
    
  def make(self):
    os.chdir( self.extractedpath+"\\vsprojects\\" )
    bufenv = dict(os.environ)    

#    includes = [self.dependencies["zlib"].getincludedir()]
#    bufenv["INCLUDE"] = ";".join(bufenv["INCLUDE"].split(";") + includes)
#    self.execute( "cmd /C set INCLUDE", env=bufenv ) #self.protobufenv)

    self.execute( "devenv.com protobuf.sln /upgrade /useenv" )
    self.call_devenv("protobuf.sln", "protoc", osenv=bufenv)
      
  def install(self):
    print("== copy include and libs")
    os.chdir( self.extractedpath+"\\vsprojects\\" )

    includedir = self.extractedpath+"\\vsprojects\\include"
    if os.path.exists(includedir):
      #remove the include dir first
      shutil.rmtree( includedir )

    self.execute( "extract_includes.bat" )
    self.copydir( "include", self.targetpath()+"\\include")
    
    #also copy descriptor.proto
    self.copyfile( self.extractedpath + "/src/google/protobuf/descriptor.proto", self.targetpath() + "/include/google/protobuf")
    
    if self.debug:
      self.copyfile( "Debug/libprotobuf.lib", self.targetpath()+"/lib")
      os.rename(self.targetpath()+"/lib/libprotobuf.lib", self.targetpath()+"/lib/libprotobufd.lib")
      self.copyfile( "Debug/libprotoc.lib", self.targetpath()+"/lib")
      os.rename(self.targetpath()+"/lib/libprotoc.lib", self.targetpath()+"/lib/libprotocd.lib")
      self.copyfile( "Debug/protoc.exe", self.targetpath()+"/bin")
      os.rename(self.targetpath()+"/bin/protoc.exe", self.targetpath()+"/bin/protocd.exe")
    else:
      self.copyfile( "Release/libprotobuf.lib", self.targetpath()+"/lib")
      self.copyfile( "Release/libprotoc.lib", self.targetpath()+"/lib")
      self.copyfile( "Release/protoc.exe", self.targetpath()+"/bin")

      # Compile and install Java interface
      os.chdir( os.path.join(self.extractedpath, "java") )
      self.execute( os.path.join(self.targetpath(), "bin", "protoc.exe") + " --java_out=src/main/java -I../src ../src/google/protobuf/descriptor.proto" )
      self.copydir( "src/main/java", self.targetpath() + "/java" )
      # Create JAR file
      # JAVA_HOME or JDK_HOME
      #try:
      #  java_path = os.environ['JAVA_HOME'] + os.path.sep + "bin"
      #except KeyError:
      #  try:
      #    java_path = os.environ['JDK_HOME'] + os.path.sep + "bin"
      #  except KeyError:
      #    java_path = ""
      #
      #java_compiler = os.path.join( java_path, "javac.exe" )
      #if( not os.path.exists( java_compiler ) ):
      #  raise BuildException("Not a valid java compiler: %s" % ( java_compiler ) )
      #java_jar = os.path.join(java_path, "jar.exe")
      #if( not os.path.exists( java_jar ) ):
      #  raise BuildException("Not a valid jar compiler: %s" % ( java_jar ) )
      java_compiler = "javac.exe"
      java_jar = "jar.exe"

      javafiles = " ".join(glob.glob(self.targetpath() + "/java/com/google/protobuf/*.java"))
      self.execute (java_compiler + " " + javafiles)
      self.execute (java_jar + " cvf " + self.targetpath() + "/java/protobuf.jar -C " + self.targetpath() + "/java com")
      print "== compiled Java API"
        #print "== [WARNING] skipped Java API compilation: could not determine JDK location (hint: set JAVA_HOME or JDK_HOME env. variable)"
      

    
    
def decider( machine, dirs ):  
  return { "Linux" : ProtoBufConfigureMakeBuilder,
           "Windows" : ProtoBufVisualStudioBuilder }[machine.platform]

BUILDER = decider

